import { stringify } from 'querystring';
import { history, Reducer, Effect } from 'umi';

import { getCaptcha,CaptchaLogin,userLogin } from '@/services/login';
import { getPageQuery } from '@/utils/utils'; 
import {LoginModelType} from '@/interface/index'


const Model: LoginModelType = {
  namespace: 'login',
  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) { 
      const response = yield call(userLogin, payload);
      
      if(response.code === 0){ 
        // 请求成功
        yield put({
          type: 'changeLoginStatus',
          payload: {
            token:response.data.access_token,
            status:"success",
          },
        }); 
        // 登录成功，跳转到首页
        history.push('/');
      }
    },

    // *CaptchaLogin({ payload }, { call }) {
    //   const response = yield call(CaptchaLogin, payload); 

    //   if(Response.code === 0){  
    //     // 请求成功
    //     yield put({
    //       type: 'CaptchaLoginStatus',
    //       payload: {
    //         token:response.data.access_token,
    //         status:"success",
    //       },
    //     }); 
    //     // 登录成功，跳转到首页
    //     history.push('/');
    //   }
    // },

    logout() {
      const { redirect } = getPageQuery();
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      sessionStorage.setItem('token',payload.token); 
      return {
        ...state,
        status: payload 
      };
    },
    // CaptchaLoginStatus(state, { payload }) {
    //   // setAuthority(payload.currentAuthority);
    //   sessionStorage.setItem('token',payload.token); 
    //   return {
    //     ...state,
    //     status: payload 
    //   };
    // }, 

  },
};

export default Model;
